package com.edu.converters;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @Author:何包蛋
 * @Date :2022/11/27 - 11 - 27 - 16:42
 */
public class DateConverters implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        System.out.println("1："+source);
        if (source != null && source.length() != 0) {
            String reg1 = "\\d{4}-\\d{1,2}-\\d{1,2}";
            String reg2 = "\\d{4}/\\d{1,2}/\\d{1,2}";
            String reg3 = "\\d{4}\\\\\\d{1,2}\\\\\\d{1,2}";

            if (Pattern.matches(reg1, source)) {
                DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = dft.parse(source);
                    return date;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else if (Pattern.matches(reg2, source)) {
                DateFormat dft = new SimpleDateFormat("yyyy/MM/dd");
                try {
                    Date date = dft.parse(source);
                    return date;
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            } else if (Pattern.matches(reg3, source)) {
                DateFormat dft = new SimpleDateFormat("yyyy\\MM\\dd");
                try {
                    Date date = dft.parse(source);
                    return date;
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

        }
        //根据需求 选择抛出异常或者返回Null
        //return null;
        throw new RuntimeException("输入的日期格式不匹配");
    }
}
